//
//  WSDiscoverController.m
//  CharonTVProject
//
//  Created by karong on 2023/6/6.
//

#import "WSDiscoverController.h"
#import "WSDiscoverRequest.h"
#import "WSChannel.h"
#import "CTMediator+WSDiscoverAction.h"
#import "WScharonTV_Part_1_Cell.h"
#import "WSFavoritesController.h"

@interface WSDiscoverController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, WSFavoritesControllerDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *searchBtn;
@property (weak, nonatomic) IBOutlet UIButton *editBtn;
@property (nonatomic, strong) NSMutableArray * dataArray;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, assign) CGFloat contentHeight;
@property (nonatomic, strong) NSMutableDictionary *contentVCDict;
@property (nonatomic, strong) WSFavoritesController * favoriteVC;

@end

@implementation WSDiscoverController

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.hidesBottomBarWhenPushed = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadHomeChannelcharonTV_Request];
    
}

- (void)viewLayout {
    [self.scrollView setContentSize:CGSizeMake(kScreenWidth * self.dataArray.count, self.contentHeight)];
}

- (UIViewController *)customPageVCWithChannel:(WSChannel *)charonTV_Channel index:(NSInteger)index {
    UIViewController * target = [[CTMediator sharedInstance]ct_showcharonTV_ChannelWithChannel:charonTV_Channel];
    target.view.frame = CGRectMake(WSScreenWidth * index, 0, self.scrollView.bounds.size.width, self.contentHeight);
    return target;
}

- (UIViewController *)favoritesVCWithChannel:(WSChannel *)charonTV_Channel index:(NSInteger)index {
    UIViewController * target = [[CTMediator sharedInstance]ct_showcharonTV_FavritesWithChannel:charonTV_Channel];
    target.view.frame = CGRectMake(WSScreenWidth * index, 0, self.scrollView.bounds.size.width, self.contentHeight);
    self.favoriteVC = target;
    self.favoriteVC.delegate = self;
    return target;
}

// 获取並且添加子控制器
- (void)setContentVCWithIndex:(NSInteger)index {
    BOOL animated = YES;
    if(self.contentVCDict.count == 0) {
        animated = NO;
    }
    BaseController *charonTV_baseVC = self.contentVCDict[@(index)];
    if(!charonTV_baseVC) {
        WSChannel * charonTV_Channel = self.dataArray[index];
        UIViewController *charonTV_baseVC;
        if (charonTV_Channel.channel_Id == 3) {
            charonTV_baseVC = [self favoritesVCWithChannel:charonTV_Channel index:index];
        }
        else {
            charonTV_baseVC = [self customPageVCWithChannel:charonTV_Channel index:index];
        }
        charonTV_baseVC.view.frame = self.scrollView.bounds;
        charonTV_baseVC.view.mj_x = WSScreenWidth * index;
        charonTV_baseVC.view.mj_y = 0;
        [self.scrollView addSubview:charonTV_baseVC.view];
        [self addChildViewController:charonTV_baseVC];
        self.contentVCDict[@(index)] = charonTV_baseVC;
    }
    [self.scrollView setContentOffset:CGPointMake(kScreenWidth * index, 0) animated:animated];
}

- (void)loadHomeChannelcharonTV_Request {
    [WSDiscoverRequest loadcharonTV_HomeChannelSuccess:^(NSArray *array) {
        self.dataArray = [[NSMutableArray alloc]initWithArray:array];
        [self viewLayout];
        self.selectIndex = 1;
        if (self.scrollView.scrollEnabled) {
            [self setContentVCWithIndex:self.selectIndex];
        }
        [self.listView reloadData];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
    }];
}
- (IBAction)searchBtnAction:(id)sender {
    UIViewController * target = [[CTMediator sharedInstance]ct_showcharonTV_SearchVC];
    [self.navigationController pushViewController:target animated:YES];
}

- (IBAction)editAction:(id)sender {
    if (self.favoriteVC) {
        [self.favoriteVC beginEdit];
        self.scrollView.scrollEnabled = NO;
    }
}
#pragma mark WSFavoritesControllerDelegate
- (void)favoritesControllerExitEdit {
    self.scrollView.scrollEnabled = YES;
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        CGFloat x = scrollView.contentOffset.x / WSScreenWidth;
        self.selectIndex = x;
        [self setContentVCWithIndex:self.selectIndex];
        [self.listView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:x inSection:0] atScrollPosition:(UICollectionViewScrollPositionCenteredHorizontally) animated:YES];
        [self.listView reloadData];
    }
}

#pragma mark UICollectionDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WScharonTV_Part_1_Cell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WScharonTV_Part_1_Cell" forIndexPath:indexPath];
    [cell setDataWithObject:self.dataArray[indexPath.row] select:self.selectIndex == indexPath.row];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    WSChannel * charonTV_Channel = self.dataArray[indexPath.row];
    CGFloat width = [charonTV_Channel.charonTV_title boundingRectWithSize:CGSizeMake(MAXFLOAT, 0.0) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:indexPath.row == self.selectIndex ? 18 : 14 weight:(UIFontWeightMedium)]} context:nil].size.width;
    return CGSizeMake(width+20, 44);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.selectIndex = indexPath.row;
    if (self.scrollView.scrollEnabled) {
        [self setContentVCWithIndex:indexPath.row];
    }
    [self.listView reloadData];
}

- (NSMutableDictionary *)contentVCDict {
    if (!_contentVCDict) {
        _contentVCDict = [[NSMutableDictionary alloc]init];
    }
    return _contentVCDict;
}

- (CGFloat)contentHeight {
    if (_contentHeight <= 0) {
        _contentHeight = WSScreenHeight - self.view.safeAreaInsets.top - 44 - self.tabBarController.tabBar.frame.size.height;
    }
    return _contentHeight;
}

- (void)setSelectIndex:(NSInteger)selectIndex {
    _selectIndex = selectIndex;
    if (selectIndex < self.dataArray.count) {
        WSChannel * charonTV_Channel = self.dataArray[selectIndex];
        self.editBtn.hidden = !(charonTV_Channel.channel_Id == 3 && self.favoriteVC.dataArrayCount > 0);
    }
}

@end
